<?php
/**
 * 转义处理特殊字符
 *
 * @param unknown_type $str
 * @return unknown
 */
function addslashes_deep($str){
	if(!get_magic_quotes_gpc()){
		$str = is_array($str)?array_map('addslashes_deep', $str):addslashes($str);
	}
	return $str;
}
/**
 * addslashes_deep 的反函数
 * 
 * @param unknown_type $str
 * @return unknown
 */
function stripslashes_deep($str){
	if(!get_magic_quotes_gpc()){
		$str = is_array($str)?array_map('stripslashes_deep', $str):stripslashes($str);
	}
	return $str;
}
/**
 * 解析获取缩略图地址
 *
 * @param String $path
 * @return String 解析完毕后的文件名称
 */
function timg($path){
	$tmp = explode('.',$path);
	return $tmp[0]."_thumb.".$tmp[1];
}
/**
 * 获取当前时间戳(含毫秒)
 *
 * @return float
 */
function microtime_float(){
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
}
/**
 * HTML 压缩函数
 *
 * @param unknown_type $content
 * @return unknown
 */
function ob_gzip(&$content){
	if(!headers_sent()&&extension_loaded("zlib")&&strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")){
		$content = gzencode($content,2);
		header("Content-Encoding: gzip");
		header("Vary: Accept-Encoding");
		header("Content-Length: ".strlen($content));
	}
	return $content;
}
/**
 * 使用反斜线引用字符串
 *
 * @param unknown_type $val
 */
function saddslashes(&$val){
	if (!get_magic_quotes_gpc()){
		return addslashes($val);
	}
	return $val;
}

/**
 * 输出异常信息
 *
 * @param unknown_type $msg
 * @param unknown_type $file
 * @param unknown_type $line
 * @param unknown_type $code
 */
function throwException($msg,$file=__FILE__,$line=__LINE__,$code=""){
	header("content-Type: text/html; charset=".$GLOBALS["ora_cfg"]["charset"]);
	echo '<table align="center" style="margin:20px;width:80%;background:#333;" cellspacing="1" cellpadding="5">';
	echo '<tr><th colspan=2 style="padding:5px;color:#fff;font-size:14px">系统发生异常</th></tr>';
	echo '<tr style="background:#fff">';
	echo '<td style="text-align:center;width:20%;font-size:13px;padding:4px;color:#333">所在文件</td>';
	printf('<td  style="line-height:24px;text-align:left;padding-left:20px;font-size:13px;padding:4px;color:blue">%s </td></tr>',$file);
	echo '<tr style="background:#fff">';
	echo '<td style="text-align:center;font-size:13px;padding:4px;color:#333">所在行数</td>';
	printf('<td  style="line-height:24px;text-align:left;padding-left:20px;font-size:13px;padding:4px;color:blue">%s </td></tr>',$line);
	echo '<tr style="background:#fff">';
	echo '<td style="line-height:24px;text-align:center;font-size:13px;padding:4px;color:#333">错误消息</td>';
	printf('<td  style="text-align:left;padding-left:20px;font-size:13px;padding:4px;color:#c22">%s </td></tr>',$msg);
	echo '</table>';
	exit();
}
/**
 * 导入类库
 *
 * @param unknown_type $path
 * @return unknown
 */
function import($path){
	$path = str_replace(".",'/',$path);
	if(file_exists(ROOT_PATH.$path."_lib.php")){
		return include_once(ROOT_PATH.$path."_lib.php");
	}else{
		throwException("类库不存在: ".ROOT_PATH.$path."_lib.php",__FILE__,__LINE__);
	}
}

/**
 * 重定向
 *
 * @param unknown_type $uri
 */
function redirect($uri,$parse=true){
	@Header("HTTP/1.1 303 See Other");
	if($parse){
		@header("Location: ".parse_uri($uri));
	}else{
		@header("Location: ".$uri);
	}
	exit();
}
/**
 * 获取系统配置信息
 *
 * @param unknown_type $key
 * @return unknown
 */
function C($key){
	return isset($GLOBALS["ora_cfg"][$key])?$GLOBALS["ora_cfg"][$key]:null;
}
/**
 * 返回带有前缀的Table名称
 *
 * @param unknown_type $str
 * @return unknown
 */
function tn($str){
	return '`'.$GLOBALS['ora_cfg']['file_suffix'].$str.'`';
}
/**
 * 加载PHP文件
 *
 * @param unknown_type $fpath
 * @return unknown
 */
function load($fpath){
	if(file_exists($fpath)){
		return include_once($fpath);
	}else{
		throwException("文件不存在: $fpath",__file__,__line__);
	}
}
/**
 * 路由模式解析主函数
 *
 * @param unknown_type $val
 */
function orain_router($val=1){
	/**
	 * 处理 非 PATH_INFO 模式下 的 映射
	 * 自动处理 url_rewrite 的启用或关闭
	 */
	if($val!=2){
		if(file_exists(ROOT_PATH.".htaccess")){
			rename(ROOT_PATH.".htaccess",ROOT_PATH.".htaccess.bak");
			$url = $GLOBALS["mod"]."-".$GLOBALS["act"];
			foreach ($GLOBALS["_param"] as $k=>$v) {
				$url .= $k."-".$v;
			}
			redirect($url);
		}
	}else{
		if(file_exists(ROOT_PATH.".htaccess.bak")){
			rename(ROOT_PATH.".htaccess.bak",ROOT_PATH.".htaccess");
			$url = $GLOBALS["mod"]."-".$GLOBALS["act"];
			foreach ($GLOBALS["_param"] as $k=>$v) {
				$url .= $k."-".$v;
			}
			redirect($url);
		}
	}
	/**
	 * 处理url参数
	 */
	switch ($val){
		case 1:
			#兼容模式: http://lan.net/index.php?mod=index&act=news&id=1&p=2
			$tmp = $_GET;
			$tmp = array_map('loseSuff',$tmp);
			$GLOBALS["mod"] = isset($tmp["mod"])?$tmp["mod"]:$GLOBALS["ora_cfg"]["default_mod"];
			unset($tmp["mod"]);
			$GLOBALS["act"] = isset($tmp["act"])?$tmp["act"]:null;
			unset($tmp["act"]);
			$GLOBALS["_param"] = $tmp;
			$sym = $GLOBALS["ora_cfg"]["url_interval"];
			foreach ($tmp as $k=>$v){
				$GLOBALS["query_uri"] .= $sym.$k."_".$v;
			}
			break;
		case 2:
			#PATH_INFO: http://lan.net/index/news/id_1/p_2.html
			if(isset($_SERVER['PATH_INFO'])&&$_SERVER['PATH_INFO']!="/"){
				#去除第一个/,url后缀.然后分割
				$tmp = explode(C("url_interval"),str_replace(C("url_suffix"),'',substr($_SERVER['PATH_INFO'],1)));
				$GLOBALS["mod"] = array_shift($tmp);
				$GLOBALS["act"] = empty($tmp)?null:array_shift($tmp);
				if($tmp){
					foreach($tmp as $k=>$v){
						$parr = explode("_",$v);
						@$GLOBALS["_param"][$parr[0]] = $parr[1];
					}
				}
			}else{
				$GLOBALS["mod"] = C("default_mod");
				$GLOBALS["act"] = null;
			}
			break;
		case 3:
			#伪静态模式: http://lan.net/index.php?index/news_1/p_2.html
			if(trim($_SERVER['QUERY_STRING'])!=""){
				$parr = explode(C("url_interval"),trim(str_replace(C("url_suffix"),'',$_SERVER['QUERY_STRING'])));
				$GLOBALS["mod"] = array_shift($parr);
				if(!empty($parr)){
					$GLOBALS["act"] = array_shift($parr);
				}
				foreach($parr as $k=>$v){
					$parr = explode("_",$v);
					$GLOBALS["_param"][$parr[0]] = $parr[1];
				}
				if($parr){
					for($j=0;$j<sizeof($parr);$j+=2){
						$GLOBALS["query_uri"] .= $sym.$parr[$j]."_".$parr[$j+1];
					}
				}
			}else{
				$GLOBALS["mod"] = C("default_mod");
			}
			break;
		default:
			throwException("路由解析错误,请检查配置文件!",__file__,__line__);
			break;
	}
}

/**
 * 替换掉 URL后缀
 *
 * @param unknown_type $val
 * @return unknown
 */
function loseSuff($val){
	return str_replace($GLOBALS['ora_cfg']['url_suffix'],'',$val);
}
/**
 * Orain uri 构造器
 * @example parse_uri("index-news-cat_id-10-id-%d|true",2)
 * 			http://xx.com/index.php?mod=index&act=news&cat_id=10&id=2 (兼容模式)
 * 			http://xx.com/index.php/index/news/cat_id_10/id_2.shtml (path_info)
 * 			http://xx.com/index/news/cat_id_10/id_2.shtml (须服务器支持htaccess)
 * 			http://xx.com/?index/news/cat_id_10/id_2.shtml (伪静态模式)
 * 			具体转换结果,以配置文件设置为准
 * 注: 在开启mk_html的情况下,该函数会判断缓存html是否可用
 * 	   可用情况下会返回html的url,否则返回 php的url
 *
 * @param string $param
 * @return string
 */
function parse_uri($param){
	$params = func_get_args();
	$has_suffix = explode("|",$params[0]);
	$params[0] = $has_suffix[0];
	$urlstr = @vsprintf($params[0],array_slice($params,1));
	$param =  explode("-",$urlstr);
	if(empty($param)){
		$param = $urlstr;
	}
	$has_suffix = (isset($has_suffix[1])&&$has_suffix[1]!=FALSE)?FALSE:true;
	switch (intval($GLOBALS['ora_cfg']["router"])){
		case 1:
			$uri = "/index.php?mod=".trim(array_shift($param))."&act=".trim(array_shift($param));
			for($j=0;$j<sizeof($param);$j+=2){
				$uri .= "&".trim($param[$j])."=".trim($param[$j+1]);
			}
			break;
		case 2:
			$sym = $GLOBALS['ora_cfg']["url_interval"];
			if($GLOBALS['ora_cfg']["support_url_rewrite"]){
				$uri ="/".array_shift($param);
				if(!empty($param)){
					$uri.= $sym.array_shift($param);
				}
			}else{
				$uri = "/index.php/".array_shift($param).$sym.array_shift($param);
			}
			for($j=0;$j<sizeof($param);$j+=2){
				$uri .= $sym.$param[$j]."_".$param[$j+1];
			}
			if($has_suffix == "true"){
				$uri .= $GLOBALS['ora_cfg']["url_suffix"];
			}
			break;
		case 3:
			$sym = $GLOBALS['ora_cfg']["url_interval"];
			$uri = "/?".array_shift($param);
			if($param){
				$uri .= $sym.array_shift($param);
			}
			for($j=0;$j<sizeof($param);$j+=2){
				$uri .= $sym.$param[$j]."_".$param[$j+1];
			}
			if($has_suffix){
				$uri .= $GLOBALS['ora_cfg']["url_suffix"];
			}
			break;
	}
	if($GLOBALS['ora_cfg']['mk_html']){
		if(!io::isExp(get_html_path($urlstr),$GLOBALS['ora_cfg']["cache_time"])){
			$tmparr = explode("-",$urlstr);
			if(!in_array($tmparr[0],$GLOBALS['ora_cfg']["mod_array"])){
				return HTTP_HOST."/archive".str_replace('?','',$uri);
			}
		}
	}
	return HTTP_HOST.$uri;
}
/**
 * 获取当前实际html的Url
 *
 */
function get_html_url(){
	if(empty($GLOBALS['_param'])){
		$p = "";
	}else{
		$p = "-".implode("-",$GLOBALS['_param']);
	}
	if(empty($GLOBALS['act'])){
		return parse_uri($GLOBALS['mod'].$p);
	}
	return parse_uri($GLOBALS['mod']."-".$GLOBALS['act'].$p);
}
/**
 * 获取当前Url String
 *
 */
function get_urlStr($url=""){
	if($url == ""){
		$url = get_url();
	}
	$f = $GLOBALS['ora_cfg']['url_interval'];
	$urlStr = "";
	$url = str_replace("index.php?","",str_replace(HTTP_HOST."/","",$url));
	$url = str_replace("?","",$url);
	$url = str_replace($GLOBALS['ora_cfg']['url_suffix'],"",$url);//去除伪静态扩展名
	if($GLOBALS['ora_cfg']['router'] == 3){//伪静态模式
		$temp = explode($f,$url);
		if(sizeof($temp)>2){
			$urlStr = array_shift($temp);//Mod
			$urlStr .= "-".array_shift($temp);//Act
			$temp = implode("-",$temp);
			$temp = str_replace("_","-",$temp);
			$urlStr.= "-".$temp;
		}else{
			$urlStr = str_replace($f,"-",$url);
		}
	}else if($GLOBALS['ora_cfg']['router'] == 2){//PATH_INFO
		$temp = explode($f,$url);
		if(sizeof($temp)>2){
			$urlStr = array_shift($temp);//Mod
			$urlStr .= "-".array_shift($temp);//Act
			$temp = implode("-",$temp);
			$temp = str_replace("_","-",$temp);
			$urlStr.= "-".$temp;
		}else{
			$urlStr = str_replace($f,"-",$url);
		}


	}else if($GLOBALS['ora_cfg']['router'] == 1){//NORMAL
		$url = explode("&",$url);
		$urlStr .= str_replace("mod=","",array_shift($url));//mod
		$urlStr .= "-".str_replace("act=","",array_shift($url));//act
		$urlStr .= "-".str_replace("=","-",implode("-",$url));
	}
	return $urlStr;
}
/**
 * 获取当前页面url的映射
 *
 * @param boolean $has_suffix
 * @return string
 */
function get_url($has_suffix=false){
	switch (intval($GLOBALS['ora_cfg']["router"])){
		case 1:
			$uri = HTTP_HOST."/index.php?mod=".$GLOBALS["mod"]."&act=".$GLOBALS["act"];
			if(isset($GLOBALS["_param"])&&!empty($GLOBALS["_param"])){
				foreach ($GLOBALS["_param"] as $k=> $v) {
					$uri .= "&$k=$v";
				}
			}
			break;
		case 2:
			$sym = C("url_interval");
			if(C("support_url_rewrite")){
				$uri = HTTP_HOST."/".$GLOBALS["mod"].$sym.$GLOBALS["act"];
			}else{
				$uri = HTTP_HOST."/index.php/".$GLOBALS["mod"].$sym.$GLOBALS["act"];
			}
			if(empty($GLOBALS["act"])){
				$uri = substr($uri,0,-1);
			}
			if(isset($GLOBALS["_param"])&&!empty($GLOBALS["_param"])){
				foreach ($GLOBALS["_param"] as $k=>$v){
					$uri .= $sym.$k."_".$v;
				}
			}
			#$uri .= C("url_suffix");
			break;
		case 3:
			$sym = $GLOBALS['ora_cfg']["url_interval"];
			$uri = HTTP_HOST."/?".$GLOBALS["mod"].$sym.$GLOBALS["act"];
			if(isset($GLOBALS["_param"])&&!empty($GLOBALS["_param"])){
				foreach ($GLOBALS["_param"] as $k=>$v){
					$uri .= $sym.$k."_".$v;
				}
			}
			#$uri .= C("url_suffix");
			break;
	}
	return $has_suffix?$uri.C("url_suffix"):$uri;
}
/**
 * 获取当前页面的完整路径
 *
 * @return unknown
 */
function get_html_path($str_url=null){
	if(empty($str_url)){
		if($GLOBALS["ora_cfg"]["router"]==2){
			$url = explode($GLOBALS['ora_cfg']["url_interval"],str_replace(HTTP_HOST."/",'',get_url()));
		}else{
			$url = $GLOBALS['mod'];
			if($GLOBALS['act']!=null){
				$url .="/".$GLOBALS['act'];
			}
			if($GLOBALS['_param']){
				foreach ($GLOBALS["_param"] as $k=> $v) {
					$url .= "/".$v."_".$k;
				}
			}
		}
		if(is_array($url)){
			return ARCHIVE_PATH.implode("/",$url).$GLOBALS['ora_cfg']["url_suffix"];
		}else{
			return ARCHIVE_PATH.$url.$GLOBALS['ora_cfg']["url_suffix"];
		}
	}else{
		$arr = explode("-",str_replace('?','',$str_url));
		$path = array_shift($arr);
		if(!empty($arr)){
			$path .="/".array_shift($arr);
			if($arr){
				for ($j=0;$j<sizeof($arr);$j+=2){
					$path .="/".$arr[$j]."_".$arr[$j+2];
				}
			}
		}
		return ARCHIVE_PATH."/".$path.$GLOBALS['ora_cfg']["url_suffix"];
	}
}
/**
	 +----------------------------------------------------------
	 * 生成验证码
	 +----------------------------------------------------------
 */
function build_verify ($length=4,$mode=1) {
	return rand_string($length,$mode);
}

/**
	 +----------------------------------------------------------
	 * 产生随机字串，可用来自动生成密码 默认长度6位 字母和数字混合
	 +----------------------------------------------------------
	 * @param string $len 长度 源自:THINK PHP
	 * @param string $type 字串类型
	 * 0 字母 1 数字 其它 混合
	 * @param string $addChars 额外字符
	 +----------------------------------------------------------
 */
function rand_string($len=6,$type='',$addChars='') {
	$str ='';
	switch($type) {
		case 0:
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
			break;
		case 1:
			$chars= str_repeat('0123456789',3);
			break;
		case 2:
			$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
			break;
		case 3:
			$chars='abcdefghijklmnopqrstuvwxyz'.$addChars;
			break;
		default :
			// 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
			$chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
			break;
	}
	if($len>10 ) {//位数过长重复字符串一定次数
		$chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
	}
	if($type!=4) {
		$chars   =   str_shuffle($chars);
		$str     =   substr($chars,0,$len);
	}else{
		// 中文随机字
		for($i=0;$i<$len;$i++){
			$str.= msubstr($chars, floor(mt_rand(0,mb_strlen($chars,'utf-8')-1)),1);
		}
	}
	return $str;
}
/**
 * 系统提示信息
 *
 * @param string $msg
 * @param string $url
 * @param boolean $autoJump
 */
function showMsg($msg,$url=null,$autoJump=false){
	if($GLOBALS['is_ajax']){
		if(!is_array($msg)){
			exit($msg);
		}else{
			$msg = implode(",",$msg);
			exit($msg);
		}
	}
	$url = empty($url)?HTTP_HOST:$url;
	$GLOBALS["tpl"]->assign("msg",$msg);
	$GLOBALS["tpl"]->assign("autoJump",$autoJump);
	$GLOBALS["tpl"]->assign("url",$url);
	if(isset($GLOBALS['__msg_tpl__'])){
		$GLOBALS['tpl']->display($GLOBALS['__msg_tpl__']);
	}else{
		$GLOBALS["tpl"]->display("msg.html");
	}
	exit();
}
/**
 * 字符串截取
 *
 * @param unknown_type $str
 * @param unknown_type $start
 * @param unknown_type $length
 * @param unknown_type $charset
 * @param unknown_type $suffix
 * @return unknown
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8",$suffix = false) {
	$str = clear_html($str);
	if ($suffix){
		$suffixStr = "…";
	}else{
		$suffixStr = "";
	}
	if (function_exists("mb_substr")){
		return mb_substr($str, $start, $length, $charset) . $suffixStr;
	}elseif (function_exists('iconv_substr')){
		return iconv_substr($str, $start, $length, $charset) . $suffixStr;
	}
	$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all($re[$charset], $str, $match);
	$slice = join("", array_slice($match[0], $start, $length));
	return $slice . $suffixStr;
}

function get_max_file_size($k=NULL){
	$tmp = 1024*1024*min(ini_get('memory_limit'), ini_get('post_max_size'), ini_get('upload_max_filesize'));
	if(is_null($k)) {
		return $tmp;
	}else{
		return min($tmp, 1024*$k);
	}
}

/**
 * 清除html代码
 *
 * @param unknown_type $str
 * @return unknown
 */

function clear_html(&$str){
	$str = html_entity_decode($str);
	$str = strip_tags($str);
	$str = preg_replace('/\<style(.*?)>.*?\<\/style\>/i','',$str);
	$str = preg_replace('/\<script(.*?)>.*?\<\/script\>/i','',$str);
	return $str;
}



?>